﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ZX.BLL.Extend;
using ZX.SYS.Library;
using ZX.EHR.Library;
using ZX.Common;
using ZX.Common.Extend;
using ZX.DBModule;

namespace ZX.BLL
{
    public class BsalSalaryItem : BaseBussnies
    {
        public override bool Insert(object entitys, out string msg)
        {
            try
            {
                //插入薪资项前,先计算出薪资项的原始表达式
                //将原始表达式的值保存到salSalaryItem的Formula字段中
                //计算薪资时直接解释原始表达式
                salSalaryItem preSalaryItem = entitys as salSalaryItem;
                string formula = SalaryFormulaResolve.GetInitialExpression(preSalaryItem.DataSource, preSalaryItem.SalarySolutionID.ToString());
                preSalaryItem.Formula = formula;
                bool bl = base.Insert(preSalaryItem, out msg);
                if (bl)
                {
                    //salSalaryItem salaryItem = entitys as salSalaryItem;
                    bool f = ModifySalaryResultTable(preSalaryItem, null, 0);
                }
                return bl;
            }
            catch (Exception ex)
            {
                try
                {
                    salSalarylErrorLog salaryErrLog = new salSalarylErrorLog();
                    BaseBussnies errBll = new BaseBussnies(salaryErrLog);
                    salaryErrLog.moduleName = this.GetType().Module.Name;
                    salaryErrLog.className = this.GetType().Name;
                    salaryErrLog.methodName = System.Reflection.MethodBase.GetCurrentMethod().Name;
                    salaryErrLog.errMsg = ex.Message;
                    salaryErrLog.errDate = DateTime.Now;
                    errBll.Insert();
                }
                catch { }
                msg = ex.Message;
                return false;
            }
        }

        public override bool Update(object entitys, out string msg)
        {
            try
            {
                //更新薪资项前,先计算出薪资项的原始表达式
                //将原始表达式的值保存到salSalaryItem的Formula字段中
                salSalaryItem salaryItem = entitys as salSalaryItem;//修改后的薪资项
                salSalaryItem tempItem = new salSalaryItem();//修改前的薪资项
                BaseBussnies itemBll = new BaseBussnies(tempItem);
                tempItem = itemBll.GetEntityByCondition("ID='" + salaryItem.ID.ToString() + "'") as salSalaryItem;
                //计算薪资时直接解释原始表达式
                string formula = SalaryFormulaResolve.GetInitialExpression(salaryItem.DataSource, salaryItem.SalarySolutionID.ToString());
                salaryItem.Formula = formula;
                //formula = formula.Replace("[J]", "+");
                //salaryItem.Formula = formula;
                bool bl = base.Update(salaryItem, out msg);
                if (bl)
                {
                    //修改薪资项名称后,薪资方案相对应的名称也要同时变更
                    if (tempItem.ItemName.Trim() != salaryItem.ItemName.Trim() || tempItem.Flag != salaryItem.Flag || tempItem.DataLength != salaryItem.DataLength || tempItem.DotLength != salaryItem.DotLength
                        || tempItem.Sort != salaryItem.Sort || tempItem.ValidDate != salaryItem.ValidDate || tempItem.ExpireDate != salaryItem.ExpireDate) //ItemName变更
                    {
                        salSalaryItem updateSalaryItem = entitys as salSalaryItem;
                        BaseBussnies updateItemBll = new BaseBussnies(updateSalaryItem);
                        IList<BaseEntity> listItems = updateItemBll.GetEntitysByCondition("ItemName='" + tempItem.ItemName + "'");
                        if (listItems != null)
                        {
                            foreach (BaseEntity entity in listItems)
                            {
                                updateSalaryItem = entity as salSalaryItem;
                                updateSalaryItem.ItemName = salaryItem.ItemName;
                                updateSalaryItem.Flag = salaryItem.Flag;
                                updateSalaryItem.FieldType = salaryItem.FieldType;
                                updateSalaryItem.DataLength = salaryItem.DataLength;
                                updateSalaryItem.DotLength = salaryItem.DotLength;
                                updateSalaryItem.Sort = salaryItem.Sort;
                                updateSalaryItem.ValidDate = salaryItem.ValidDate;
                                updateSalaryItem.ExpireDate = salaryItem.ExpireDate;
                                updateItemBll.Update(updateSalaryItem);
                            }
                        }
                    }
                    //薪资项表达式改变后，包含该薪资项的薪资项的表达式也要发生改变
                    ModifySalaryItemFormular(salaryItem);
                    //if (tempItem.DataSource != salaryItem.DataSource)
                    //{
                    //    ModifySalaryItemFormular(salaryItem);
                    //}
                    //更新薪资结果表结构
                    bool f = ModifySalaryResultTable(salaryItem, tempItem, 1);
                }
                return bl;
            }
            catch (Exception ex)
            {
                try
                {
                    salSalarylErrorLog salaryErrLog = new salSalarylErrorLog();
                    BaseBussnies errBll = new BaseBussnies(salaryErrLog);
                    salaryErrLog.moduleName = this.GetType().Module.Name;
                    salaryErrLog.className = this.GetType().Name;
                    salaryErrLog.methodName = System.Reflection.MethodBase.GetCurrentMethod().Name;
                    salaryErrLog.errMsg = ex.Message;
                    salaryErrLog.errDate = DateTime.Now;
                    errBll.Insert();
                }
                catch { }
                msg = ex.Message;
                return false;
            }
        }

        //更新与该薪资项相关联的薪资项表达式
        private void ModifySalaryItemFormular(salSalaryItem salaryItem)
        {
            salSalaryItem tempSalSalaryItem = new salSalaryItem();
            BaseBussnies tempSalaryBll = new BaseBussnies(tempSalSalaryItem);
            IList<BaseEntity> tempSalaryItemList = tempSalaryBll.GetEntitysByCondition("DataSource like '%" + salaryItem.ItemNotes.Trim() + "%'");
            if (tempSalaryItemList != null)
            {
                salSalaryItem instance = new salSalaryItem();
                BaseBussnies bll = new BaseBussnies(instance);
                foreach (BaseEntity entity in tempSalaryItemList)
                {
                    salSalaryItem salentity = entity as salSalaryItem;
                    string entityformula = SalaryFormulaResolve.GetInitialExpression(salentity.DataSource, salentity.SalarySolutionID.ToString());
                    salentity.Formula = entityformula; ;
                    bll.Update(salentity);
                    ModifySalaryItemFormular(salentity);
                }
            }
        }

        public override bool delete(string condition)
        {
            try
            {
                salSalaryItem salaryItem = new salSalaryItem();//删除的薪资项
                BaseBussnies itemBll = new BaseBussnies(salaryItem);
                salaryItem = itemBll.GetEntityByCondition(condition) as salSalaryItem;
                bool bl = base.delete(condition);
                if (bl)
                {
                    //删除薪资方案中的名称为ItemName的薪资项
                    itemBll.delete("ItemName='" + salaryItem.ItemName + "'");
                    //修改薪资结果表结构
                    bool f = ModifySalaryResultTable(salaryItem, null, 2);
                }
                return bl;
            }
            catch (Exception ex)
            {
                try
                {
                    salSalarylErrorLog salaryErrLog = new salSalarylErrorLog();
                    BaseBussnies errBll = new BaseBussnies(salaryErrLog);
                    salaryErrLog.moduleName = this.GetType().Module.Name;
                    salaryErrLog.className = this.GetType().Name;
                    salaryErrLog.methodName = System.Reflection.MethodBase.GetCurrentMethod().Name;
                    salaryErrLog.errMsg = ex.Message;
                    salaryErrLog.errDate = DateTime.Now;
                    errBll.Insert();
                }
                catch { }
                return false;
            }
        }

        /// <summary>
        /// 当原始薪资项目发生变化时动态修改薪资结果表结构
        /// </summary>
        /// <param name="salaryItem">薪资对象</param>
        /// <param name="flag">标识，0－新增，1－修改，2－删除</param>
        private bool ModifySalaryResultTable(salSalaryItem salaryItem,salSalaryItem preSalaryItem, byte flag)
        {
            bool f = false;
            try
            {
                //增加字段：alter talbe 表名 add 字段名 类型(宽度[,小数位] )
                //修改字段：alter table 表名 alter column 字段名 类型(宽度[,小数位] )
                //重命名字段：EXEC sp_rename 'salSalaryItem.CharValue','CharValue','COLUMN'
                //删除字段：alter table 表名 drop column 字段名
                string sql = string.Empty;
                string fieldType = salaryItem.FieldType;
                BaseBussnies bll = new BaseBussnies();
                switch (flag)
                {
                    case 0: //新增
                        sql = "alter table salEmployeeSalaryResult add " + salaryItem.ItemName + " ";
                        //if (fieldType == "varchar")
                        //{
                        //    fieldType = "varchar(50)";
                        //}
                        //else
                        //{
                        //    int len = salaryItem.DataLength == 0 ? 9 : salaryItem.DataLength;
                        //    int dotLen = salaryItem.DataLength == 0 ? 2 : salaryItem.DotLength;
                        //    fieldType = "numeric(" + len + ", " + dotLen + ")";
                        //}
                        fieldType = "varchar(50)";
                        sql += fieldType;
                        break;
                    case 1: //修改
                        try
                        {
                            //重新命名字段名
                            sql = "EXEC sp_rename 'salEmployeeSalaryResult." + preSalaryItem.ItemName + "','" + salaryItem.ItemName + "','COLUMN'";
                            bll.RunSqlCommand(sql);
                            //修改字段类型
                            //if (fieldType == "varchar")//字段类型
                            //{
                            //    fieldType = "varchar(50)";
                            //}
                            //else
                            //{
                            //    int len = salaryItem.DataLength == 0 ? 9 : salaryItem.DataLength;
                            //    int dotLen = salaryItem.DataLength == 0 ? 2 : salaryItem.DotLength;
                            //    fieldType = "numeric(" + len + ", " + dotLen + ")";
                            //}
                            fieldType = "varchar(50)";
                            sql = "alter table salEmployeeSalaryResult alter column " + salaryItem.ItemName + " ";
                            sql += fieldType;
                            bll.RunSqlCommand(sql);
                            f = true;
                        }
                        catch(Exception ex)
                        {
                            f = false;
                        }
                        break;
                    case 2: //删除
                        sql = "alter table salEmployeeSalaryResult drop column " + salaryItem.ItemName;
                        break;
                }
                if (sql != string.Empty)
                {
                    try
                    {
                        bll.RunSqlCommand(sql);
                        f = true;
                    }
                    catch {
                        f = false;
                    }
                }
            }
            catch(Exception ex){
                try
                {
                    salSalarylErrorLog salaryErrLog = new salSalarylErrorLog();
                    BaseBussnies errBll = new BaseBussnies(salaryErrLog);
                    salaryErrLog.moduleName = this.GetType().Module.Name;
                    salaryErrLog.className = this.GetType().Name;
                    salaryErrLog.methodName = System.Reflection.MethodBase.GetCurrentMethod().Name;
                    salaryErrLog.errMsg = ex.Message;
                    salaryErrLog.errDate = DateTime.Now;
                    errBll.Insert();
                }
                catch { }
            }
            if (f)
            {
                bool ff = CreateSalaryResultView();
                if (ff)
                {
                    CreateSalaryResultListView();
                }
            }
            return f;
        }

        /// <summary>
        /// 生成员工工资表视图
        /// </summary>
        /// <returns></returns>
        private bool CreateSalaryResultView()
        {
            try
            {
                BaseBussnies bll = new BaseBussnies();
                //先删除视图
                string sql = "IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[V_salEmployeeSalaryResult]')) DROP VIEW [dbo].[V_salEmployeeSalaryResult]";
                bll.RunSqlCommand(sql);
                //获取ID，SalarySultionID，EmployeeID，YearMonth，BeginDate，EndDate，CalDate以外的字段
                //获取表薪资项所有列
                string sqlsys = "select a.name from sys.columns a,sys.types b where [object_id]=object_id('salEmployeeSalaryResult') and a.system_type_id=b.system_type_id";
                string otherfield = string.Empty;
                System.Data.DataTable dt = bll.GetDataBySqlComm(sqlsys);
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    string temp = dt.Rows[i][0].ToString();
                    if ("ID,SalarySultionID,EmployeeID,YearMonth,BeginDate,EndDate,CalDate,AddUser".Contains(temp)) continue;
                    otherfield += "a." + temp + ",";
                }
                otherfield = otherfield.Substring(0, otherfield.Length - 1);
                sql = "CREATE VIEW V_salEmployeeSalaryResult AS select a.ID,a.EmployeeID,a.AddUser,b.DeptID,a.YearMonth,b.EmployeeCode,b.CName,b.DeptName,b.PostName,b.DeptPath," + otherfield + " from salEmployeeSalaryResult a left join (select ID,CName,EmployeeCode,DeptName,PostName,DeptID,DeptPath from V_hrEmployee)b on a.EmployeeID=b.ID";
                //创建视图
                bll.RunSqlCommand(sql);
                return true;
            }
            catch(Exception ex)
            {
                try
                {
                    salSalarylErrorLog salaryErrLog = new salSalarylErrorLog();
                    BaseBussnies errBll = new BaseBussnies(salaryErrLog);
                    salaryErrLog.moduleName = this.GetType().Module.Name;
                    salaryErrLog.className = this.GetType().Name;
                    salaryErrLog.methodName = System.Reflection.MethodBase.GetCurrentMethod().Name;
                    salaryErrLog.errMsg = ex.Message;
                    salaryErrLog.errDate = DateTime.Now;
                    errBll.Insert();
                }
                catch { }
            }
            return false;
        }

        /// <summary>
        /// 创建薪资结果列表显示视图
        /// </summary>
        /// <returns></returns>
        private bool CreateSalaryResultListView()
        {
            BaseBussnies bll = new BaseBussnies();
            //删除之前的列表视图
            string sql = "delete from Set_DataListTemplate where EntityName='V_salEmployeeSalaryResult'";
            bll.RunSqlCommand(sql);
            //创建新列表视图
            string sqlsys = "select name from sys.columns where [object_id]=object_id('V_salEmployeeSalaryResult')";
            System.Data.DataTable dt = bll.GetDataBySqlComm(sqlsys);
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                string temp = dt.Rows[i][0].ToString();
                if (temp == "EmployeeID" || temp == "DeptID" || temp == "DeptPath" || temp == "AddUser") continue;
                string caption = string.Empty;
                int width = 80;
                if (temp == "ID")
                {
                    width = 0;
                }
                else if (temp == "YearMonth")
                {
                    caption = "发放年月";
                    width = 50;
                }
                else if (temp == "EmployeeCode")
                {
                    caption = "工号";
                }
                else if (temp == "CName")
                {
                    caption = "姓名";
                }
                else if (temp == "DeptName")
                {
                    width = 120;
                    caption = "部门";
                }
                else if (temp == "PostName")
                {
                    width = 150;
                    caption = "职位";
                }
                else
                {
                    salSalaryItem salaryItem = new salSalaryItem();
                    BaseBussnies itemBll = new BaseBussnies(salaryItem);
                    salaryItem = itemBll.GetEntityByCondition("ItemName='" + temp + "'") as salSalaryItem;
                    caption = salaryItem.ItemNotes;
                }
                sql = "insert into Set_DataListTemplate (EntityName,THCaption,Field,Width,iOrder,IsVisiable,IsFixed) values('V_salEmployeeSalaryResult','" + caption + "','" + temp + "'," + width + "," + i + ",'Y','Y')";
                if (temp == "AttendanceDebit")
                {
                    sql = "insert into Set_DataListTemplate (EntityName,THCaption,Field,Width,iOrder,IsVisiable,IsFixed,DataFormatter) values('V_salEmployeeSalaryResult','" + caption + "','" + temp + "'," + width + "," + i + ",'Y','Y','fnViewDeail')";
                }
                bll.RunSqlCommand(sql);
            }           
            return true;
        }
    }
}